package datenverwaltung;

import java.awt.Cursor;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.swing.JDialog;
import javax.swing.JProgressBar;

public class MeldungErstellenThread extends Thread implements DBVerbindung {

	private Meldung m;
	private JProgressBar bar;
	private JDialog container;

	public MeldungErstellenThread(Meldung m, JProgressBar bar, JDialog container) {
		super();
		this.m = m;
		this.bar = bar;
		this.container = container;
	}

	@Override
	public Connection getConnection() throws Exception {
		Connection connection;
		Class.forName("com.mysql.jdbc.Driver");
		connection = DriverManager.getConnection(DB_CONNECTION_URL,
				DB_USERNAME, DB_PASSWORD);
		return connection;
	}

	@Override
	public ResultSet executeStatementOnDB(String stmnt) throws Exception {
		Connection connection = getConnection();
		Statement statement = connection.createStatement();
		statement.executeUpdate(stmnt);
		return null;
	}

	@Override
	public void run() {
		String insert = "insert into meldung values(0,"
				+ m.getKoordinaten().getLongitude() + ","
				+ m.getKoordinaten().getLatitude() + ",\"" + m.getOrt()
				+ "\",\""
				+ removeNanosFromTimestamp(m.getErstellzeitpunkt().toString())
				+ "\",\"" + m.getArt() + "\",true,0,0,\"" + m.getBeschreibung()
				+ "\"," + m.getTracker_id() + ");";

		try {
			executeStatementOnDB(insert);
		} catch (Exception e) {
			e.printStackTrace();
		}
		bar.setIndeterminate(false);
		container.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
		container.dispose();
	}

	/**
	 * Entfernt die Nanosekunden vom Timestamp.
	 * 
	 * @param timestamp
	 * @return
	 */
	public String removeNanosFromTimestamp(String timestamp) {
		return timestamp.substring(0, timestamp.indexOf("."));
	}

}
